import 'package:flutter/material.dart';

class FramesAnimation extends StatefulWidget {
  //const FramesAnimation({super.key});
  FramesAnimation({
    Key? key, //记录组件状态的
    this.initIndex = 0,
    required this.images,
  }) : super(key: key);

  /// 当前帧动画索引（标记）
  final int initIndex;

  /// 帧动画图片
  final List images;
  @override
  State<FramesAnimation> createState() => FramesAnimationState();
}

//with SingleTickerProviderStateMixin混入
class FramesAnimationState extends State<FramesAnimation>
    with SingleTickerProviderStateMixin {
  ///动画控制器
  late AnimationController _animationController;

  ///动画对象
  late Animation _animation;

  @override
  void initState() {
    // 测试：7秒钟播放7个色块(7帧)
    //创建动画控制器
    //vsync防止屏幕外的动画占用资源
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );
    //创建动画对象
    _animation = Tween(
      begin: 0.0,
      end: (widget.images.length - 1).toDouble(),
    ).animate(_animationController);
    //监听动画刷新：flutter每一秒钟刷新60次，所以动画的刷新次数为60
    //动画刷新次数与动画时长有关，动画时长越长，动画刷新次数越少
    _animationController.addListener(() {
      //如果监听到动画刷新，则刷新当前组件
      setState(() {});
    });
    //默认启动动画
    if (widget.initIndex == 0) {
      startAnimation();
    }
    super.initState();
  }

  @override
  void dispose() {
    //释放动画控制器
    _animationController.dispose();
    super.dispose();
  }

  //启动动画
  // void startAnimation() {
  //   _animationController.forward();
  // }
  //箭头函数
  void startAnimation() => _animationController.forward();

  //重置动画
  void resetAnimation() {
    _animationController.reset();
  }

  // List frames = [
  //   Container(width: 20, height: 20, color: Colors.red),
  //   Container(width: 20, height: 20, color: Colors.orange),
  //   Container(width: 20, height: 20, color: Colors.blue),
  //   Container(width: 20, height: 20, color: Colors.green),
  //   Container(width: 20, height: 20, color: Colors.purple),
  //   Container(width: 20, height: 20, color: Colors.pink),
  //   Container(width: 20, height: 20, color: Colors.yellow),
  // ];

  @override
  Widget build(BuildContext context) {
    // 输出帧动画的取值
    //print(_animation.value);

    int framesIndex = _animation.value.floor();
    return Container(
      // 读取并展示当前帧
      //child: frames[framesIndex],
      child: widget.images[framesIndex],
    );
  }
}
